package com.fivestar.finance.app.ui.main;


import android.app.Fragment;
import android.content.Intent;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.design.widget.NavigationView;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.widget.Toolbar;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.TextView;

import com.fivestar.finance.app.R;
import com.fivestar.finance.app.injector.HasComponent;
import com.fivestar.finance.app.ui.BaseActivity;
import com.fivestar.finance.app.ui.account.MyActivity;
import com.fivestar.finance.app.ui.box.HomeBoxFragment;
import com.fivestar.finance.library.utils.ResourceUtil;
import com.fivestar.finance.library.utils.StatusBarUtil;
import com.fivestar.finance.library.widget.CircleImageView;

import javax.inject.Inject;

import butterknife.BindView;

/**
 * 简要描述
 *
 * @author Derek.Kidd
 * @version V1.0.0
 * @date 2016/8/23 10:41
 */
public class MainActivity extends BaseActivity implements IMainView, HasComponent<MainComponent> {

    @BindView(R.id.toolbar)
    Toolbar toolbar;

    @BindView(R.id.drawerLayout)
    DrawerLayout drawerLayout;

    @BindView(R.id.navigation_view)
    NavigationView mNavigationView;


    private ActionBarDrawerToggle mActionBarDrawerToggle;

    @Inject
    MainPresenter mPresenter;

    private MainComponent mMainComponent;


    private int count = 0;

    @Override
    protected int initContentView() {
        return R.layout.activity_main;
    }

    @Override
    protected boolean isApplyStatusBarTranslucency() {
        return false;
    }

    @Override
    protected boolean isApplyStatusBarColor() {
        return false;
    }

    @Override
    public void initInjector() {
        mMainComponent = DaggerMainComponent.builder()
                .applicationComponent(getApplicationComponent())
                .activityModule(getActivityModule()).mainModule(new MainModule(this))
                .build();
        mMainComponent.inject(this);
    }

    @Override
    public void initUiAndListener() {

        setSupportActionBar(toolbar);
        getSupportActionBar().setHomeButtonEnabled(true); //设置返回键可用
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        setTitle("百宝箱");


        CircleImageView ivIcon = (CircleImageView) mNavigationView.getHeaderView(0).findViewById(R.id.cat_avatar);


        //TODO
        mNavigationView.getHeaderView(0).findViewById(R.id.ivCover).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                showUserProfileUi(null);
            }
        });


        //创建返回键，并实现打开关/闭监听
        mActionBarDrawerToggle = new ActionBarDrawerToggle(this, drawerLayout, toolbar, R.string.open, R.string.close);
        mActionBarDrawerToggle.syncState();
        drawerLayout.setDrawerListener(mActionBarDrawerToggle);

        StatusBarUtil.setColorForDrawerLayout(this, drawerLayout, ResourceUtil.getThemeColor
                (this), 0);

        mNavigationView.setItemIconTintList(null);//设置菜单图标恢复本来的颜色
        setupDrawerContent();
        getFragmentManager().beginTransaction()
                .replace(R.id.content,
                        new HomeBoxFragment())
                .commit();

        mPresenter.attachView(this);
    }

    private void setupDrawerContent() {
        mNavigationView.setNavigationItemSelectedListener(
                new NavigationView.OnNavigationItemSelectedListener() {
                    @Override
                    public boolean onNavigationItemSelected(MenuItem menuItem) {
                        mPresenter.onNavigationClick(menuItem);
                        return true;
                    }
                });
    }


    /**
     * 刷新通知图标
     *
     * @param count
     */
    //    @Override
    public void renderNotification(int count) {
        this.count = count;
        invalidateOptionsMenu();
    }

    @Override
    public boolean onCreateOptionsMenu(final Menu menu) {
        getMenuInflater().inflate(R.menu.menu_main, menu);
        MenuItem menuItem = menu.findItem(R.id.action_notification);
        menuItem.setIcon(buildCounterDrawable(count, R.drawable.ic_menu_notification));
        return true;
    }

    @Override
    protected void onPostCreate(Bundle savedInstanceState) {
        super.onPostCreate(savedInstanceState);
        mActionBarDrawerToggle.syncState();
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
                drawerLayout.openDrawer(GravityCompat.START);
                break;
            case R.id.action_notification:
//                mPresenter.onNotificationClick();
                break;
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    public void onBackPressed() {
        mPresenter.exist();
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        mActionBarDrawerToggle.onConfigurationChanged(newConfig);
    }

    @Override
    public void closeDrawers() {
        drawerLayout.closeDrawers();
    }

    @Override
    public void showFragment(Fragment fragment) {
        getFragmentManager().beginTransaction().replace(R.id.content, fragment).commit();
    }

    @Override
    public void setTitle(CharSequence title) {
        super.setTitle(title);
    }

    @Override
    public void showMessageUi() {

    }

    @Override
    public void showUserProfileUi(String uid) {
        Intent intent = new Intent(MainActivity.this, MyActivity.class);
        startActivity(intent);
    }

    @Override
    public void showLoginUi() {

    }

    @Override
    public void showAccountUi() {

    }

    @Override
    public void showSettingUi() {

    }

    @Override
    public void showFeedBackUi() {

    }

    @Override
    public void showAboutUi() {

    }

    /**
     * 生成通知图标
     *
     * @param count
     * @param backgroundImageId
     * @return
     */
    private Drawable buildCounterDrawable(int count, int backgroundImageId) {
        LayoutInflater inflater = LayoutInflater.from(this);
        View view = inflater.inflate(R.layout.notification_count_layout, null);
        view.setBackgroundResource(backgroundImageId);
        TextView tvCount = (TextView) view.findViewById(R.id.tvCount);
        if (count == 0) {
            tvCount.setVisibility(View.GONE);
        } else {
            tvCount.setVisibility(View.VISIBLE);
            tvCount.setText(String.valueOf(count));
        }

        view.measure(View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED),
                View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED));
        view.layout(0, 0, view.getMeasuredWidth(), view.getMeasuredHeight());

        view.setDrawingCacheEnabled(true);
        view.setDrawingCacheQuality(View.DRAWING_CACHE_QUALITY_HIGH);
        Bitmap bitmap = Bitmap.createBitmap(view.getDrawingCache());
        view.setDrawingCacheEnabled(false);

        return new BitmapDrawable(getResources(), bitmap);
    }

    @Override
    public MainComponent getComponent() {
        return mMainComponent;
    }
}
